﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections;

namespace Carbon.Web.Forms.jQueryForms
{
    public interface IListEditorItemCollection : IModelValue, IEnumerable//IEnumerable<IListEditorItem>
    {
        String GetDisplayName(Object data);
    }

    [Serializable]
    public class ListEditorItemCollection<T> : List<ListEditorItem<T>>, IListEditorItemCollection//, IEnumerable<IListEditorItem>
    {
        public virtual object Clone()
        {
            ListEditorItemCollection<T> listItemCollection = new ListEditorItemCollection<T>(this.NameGenerator);
            CloneListEditorItemCollectionProperties(listItemCollection);
            return listItemCollection;
        }

        protected void CloneListEditorItemCollectionProperties(ListEditorItemCollection<T> collection)
        {
            collection.m_NameGenerator = m_NameGenerator;
            collection.AddRange(this.Select(i => i.Clone()));
        }

        public String GetDisplayName(Object data)
        {
            String value = NameGenerator((T)data);
            return value == null ? string.Empty : value;
        }

        private Func<T, String> m_NameGenerator = default(Func<T, String>);
        public Func<T, String> NameGenerator
        {
            get
            {
                return m_NameGenerator;
            }
        }

        public ListEditorItemCollection(IEnumerable<ListEditorItem<T>> collection, Func<T, string> nameGenerator)
            : base(collection)
        {
            if (nameGenerator == null) throw new ArgumentNullException("nameGenerator");

            this.m_NameGenerator = nameGenerator;
        }

        public ListEditorItemCollection(int capacity, Func<T, string> nameGenerator)
            : base(capacity)
        {
            if (nameGenerator == null) throw new ArgumentNullException("nameGenerator");

            this.m_NameGenerator = nameGenerator;
        }

        public ListEditorItemCollection(Func<T, string> nameGenerator)
            : base()
        {
            if (nameGenerator == null) throw new ArgumentNullException("nameGenerator");

            this.m_NameGenerator = nameGenerator;
        }

        public ListEditorItemCollection(IEnumerable<T> objects, Func<T, string> nameGenerator, bool defaultSelected)
        {
            if (nameGenerator == null) throw new ArgumentNullException("nameGenerator");

            this.m_NameGenerator = nameGenerator;

            this.AddRange(objects.Select(i => new ListEditorItem<T>() { Model = i, Selected = defaultSelected }));
        }

        #region IEnumerable<IListEditorItem> Members

        #endregion
    }
}
